package com.example.piece.ui.fragment

import android.content.pm.ActivityInfo
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.example.base.ext.dip2px
import com.example.base.ext.getViewModel
import com.example.base.ui.activity.BaseActivity
import com.example.base.ui.fragment.BaseFragment
import com.example.base.ui.view.DividerItemDecoration
import com.example.base.vm.onError
import com.example.piece.R
import com.example.piece.constant.Key
import com.example.piece.databinding.FragmentTextBinding
import com.example.piece.databinding.ItemHomeRecommendationVideoBinding
import com.example.piece.entity.AttentionEntity
import com.example.piece.tools.UtilsPlay
import com.example.piece.ui.adapter.HomeRecommendationAdapter
import com.example.piece.vm.HelperViewModel
import com.example.piece.vm.HomeViewModel
import com.example.piece.vm.JokesViewModel
import com.example.piece.vm.UserViewModel
import com.kongzue.dialogx.dialogs.TipDialog
import com.wenming.library.encryption.imp.AESEncode
import xyz.doikki.videocontroller.StandardVideoController
import xyz.doikki.videocontroller.component.*
import xyz.doikki.videoplayer.player.AbstractPlayer
import xyz.doikki.videoplayer.player.VideoView
import xyz.doikki.videoplayer.player.VideoViewManager

/**
 * 纯文
 */
class TextFragment : BaseFragment<FragmentTextBinding>() {


    companion object {
        fun newInstance(): Fragment {
            val fragment = TextFragment()
            return fragment
        }

        /**
         * 当前播放的位置
         */
        protected var mCurPos = -1

        /**
         * 上次播放的位置，用于页面切回来之后恢复播放
         */
        protected var mLastPos = mCurPos
        protected var mVideoView: VideoView<AbstractPlayer>? = null
        protected var mController: StandardVideoController? = null
        protected var mErrorView: ErrorView? = null
        protected var mCompleteView: CompleteView? = null
        protected var mTitleView: TitleView? = null
        var mCurrentIndex = 0
    }
    private val userViewModel: UserViewModel by lazy {
        getViewModel<UserViewModel>()
    }
    private val helperViewModel: HelperViewModel by lazy {
        getViewModel<HelperViewModel>()
    }
    override fun getContentRes(): Int=R.layout.fragment_text

    /**  类型 Adapter  **/
    private val homeRecommendationAdapter: HomeRecommendationAdapter by lazy {
        val adapter = HomeRecommendationAdapter(emptyList(),userViewModel,jokesViewModel,helperViewModel,this.activity as BaseActivity<ViewDataBinding>)
        context?.let {
            mBinding.rv.addItemDecoration(DividerItemDecoration(context,
                DividerItemDecoration.HORIZONTAL_LIST,
                it.dip2px(10f).toInt(),
                Color.parseColor("#f4f4f4")))
        }
        mBinding.rv.adapter = adapter
        adapter
    }

    //是否是刷新
    var isFresh = false

    private val homeViewModel: HomeViewModel by lazy {
        getViewModel<HomeViewModel>()
    }
    private val jokesViewModel: JokesViewModel by lazy {
        getViewModel<JokesViewModel>()
    }

    override fun initData(view: View, savedInstanceState: Bundle?) {
        super.initData(view, savedInstanceState)

        //初始化播放器
        initVideoView()
        homeRecommendationAdapter.loadMoreModule.isAutoLoadMore = true
        homeRecommendationAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = false
        getHomeText()
        homeRecommendationAdapter.loadMoreModule.setOnLoadMoreListener {
            getHomeText()
        }
        homeRecommendationAdapter.setOnItemChildClickListener(object : OnItemChildClickListener {
            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                startPlay(position)
            }
        }
        )
        mBinding.srl.setOnRefreshListener {
            isFresh=true
            getHomeText() }

        mBinding.rv.addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {

            }

            override fun onChildViewDetachedFromWindow(view: View) {
                val playerContainer = view.findViewById<FrameLayout>(R.id.player_container)
                val v = playerContainer?.getChildAt(0)
                if (v != null && v === mVideoView && mVideoView?.isFullScreen() != true) {
                    releaseVideoView()
                }
            }

        })
        mBinding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    autoPlayVideo(recyclerView)

                    Glide.with(this@TextFragment).resumeRequests();
                } else {
                    Glide.with(this@TextFragment).pauseRequests();
                }
            }
        })
    }
    private fun autoPlayVideo(recyclerview: RecyclerView?) {
        recyclerview?.let {
            val childCount = it.childCount
            loop@ for (i in 0 until childCount) {
                val itemView = it.getChildAt(i)

                var binding =
                    DataBindingUtil.getBinding<ViewDataBinding>(itemView)
                if (binding is ItemHomeRecommendationVideoBinding) {
                    val rect = Rect()
                    binding?.playerContainer?.getLocalVisibleRect(rect)
                    val height = binding?.playerContainer?.height
                    if (rect.top === 0 && rect.bottom === height) {
                        binding?.position?.let { it1 -> startPlay(it1) }
                        return
                    }
                }

            }

        }

    }

    protected fun initVideoView() {
        mVideoView = context?.let { VideoView<AbstractPlayer>(it) }
        mVideoView?.setOnStateChangeListener(object : VideoView.SimpleOnStateChangeListener() {
            override fun onPlayStateChanged(playState: Int) {
                //监听VideoViewManager释放，重置状态
                if (playState == VideoView.STATE_IDLE) {
                    UtilsPlay.removeViewFormParent(mVideoView)
                    mLastPos = mCurPos
                    mCurPos = -1
                }
            }
        })
        mController = context?.let { StandardVideoController(it) }
        mErrorView = ErrorView(activity)
        mController?.addControlComponent(mErrorView)
        mCompleteView = context?.let { CompleteView(it) }
        mController?.addControlComponent(mCompleteView)
        mTitleView = context?.let { TitleView(it) }
        mController?.addControlComponent(mTitleView)
        mController?.addControlComponent(context?.let { VodControlView(it) })
        mController?.addControlComponent(context?.let { GestureView(it) })
        mController?.setEnableOrientation(true)
        mVideoView?.setVideoController(mController)
    }

    private fun startPlay(position: Int) {
        if (mCurPos == position) return
        if (mCurPos != -1) {
            releaseVideoView()
        }
        val videoBean: AttentionEntity = homeRecommendationAdapter.data[position]
        if (videoBean.joke.type.toInt()<3){
            return

        }
        //边播边存
//        String proxyUrl = ProxyVideoCacheManager.getProxy(getActivity()).getProxyUrl(videoBean.getUrl());
//        mVideoView.setUrl(proxyUrl);
        val videoUrl =
            AESEncode.Decrypt(
                videoBean?.joke?.videoUrl?.split(",")?.get(0)?.replace("ftp://", "").toString().trim(),
                "cretinzp**273846"
            )
        mVideoView?.setLooping(true)

        mVideoView?.setUrl(videoUrl)

        Log.e("dddddddddddddvideoUrl", videoUrl + "")

        mTitleView?.setTitle(videoBean.joke.videoTime)
        val itemView: View = mBinding.rv.layoutManager?.findViewByPosition(position) ?: return
        val viewHolder =
            DataBindingUtil.getBinding<ItemHomeRecommendationVideoBinding>(itemView)
        //把列表中预置的PrepareView添加到控制器中，注意isDissociate此处只能为true, 请点进去看isDissociate的解释
        mController?.addControlComponent(viewHolder?.prepareView, true)
        UtilsPlay.removeViewFormParent(mVideoView)
        viewHolder?.playerContainer?.addView(mVideoView, 0)
        //播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它
        getVideoViewManager()?.add(mVideoView, Key.DataKey.HOME_LIST)
        mVideoView?.start()
        mCurPos = position
    }

    private fun releaseVideoView() {
        mVideoView?.release()
        if (mVideoView?.isFullScreen() == true) {
            mVideoView?.stopFullScreen()
        }
        if (activity?.requestedOrientation !== ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        mCurPos = -1
    }
    //获取最新
    private fun getHomeText() {
        homeViewModel.homeText(null) {
            if (it.code == 200) {

                val data = it.data;
                homeRecommendationAdapter.loadMoreModule.loadMoreComplete()
                if (isFresh){
                    homeRecommendationAdapter.setList(data.toMutableList())
                    releaseVideoView()
                    mCurPos = -2
                    //  autoPlayVideo(mBinding.rv)
                    mBinding.rv.smoothScrollBy(0,1)

                }else{
                    homeRecommendationAdapter.addData(data.toMutableList())

                }
                isFresh=false

            } else {
                TipDialog.show(it.msg)
                homeRecommendationAdapter.loadMoreModule.loadMoreFail()

            }
            mBinding.srl.isRefreshing = false

        } onError {
            TipDialog.show(it)
            homeRecommendationAdapter.loadMoreModule.loadMoreFail()
            mBinding.srl.isRefreshing = false

        }
    }

    /**
     * 子类可通过此方法直接拿到VideoViewManager
     */
    protected fun getVideoViewManager(): VideoViewManager? {
        return VideoViewManager.instance()
    }

    override fun onPause() {
        super.onPause()
        pause()
    }

    /**
     * 由于onPause必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onPause的逻辑
     */
    protected fun pause() {
        releaseVideoView()
    }

    override fun onResume() {
        super.onResume()
        resume()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            releaseVideoView()
            mCurPos = -2
            // autoPlayVideo(mBinding.rv)
            mBinding.rv.smoothScrollBy(0,1)
        } else {
            releaseVideoView()
        }
    }

    /**
     * 由于onResume必须调用super。故增加此方法，
     * 子类将会重写此方法，改变onResume的逻辑
     */
    protected fun resume() {
        if (mLastPos == -1) return
        if (mCurrentIndex !== 1) return
        //恢复上次播放的位置
        startPlay(mLastPos)
    }



}